//
//  FinishedTask.m
//  RRQS
//
//  Created by kyjun on 16/3/29.
//
//

#import "FinishedTask.h"
#import "FinishedHeader.h"
#import "FinishedCell.h"
#import "MFinishedTask.h"
#import "FinishedTaskDetail.h"
#import <DZNEmptyDataSet/UIScrollView+EmptyDataSet.h>
#import "Pager.h"

@interface FinishedTask ()<DZNEmptyDataSetSource,DZNEmptyDataSetDelegate>

@property(nonatomic,strong) UIView* headerView;
@property(nonatomic,strong) UILabel* labelTitle;

@property(nonatomic,strong) NSString* cellIdentifier;
@property(nonatomic,strong) NSString* headerIdentifier;

@property(nonatomic,strong) NSMutableArray* arrayData;

@property(nonatomic,strong) Pager* page;
@end

@implementation FinishedTask

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"已完成的任务";
    self.cellIdentifier = @"FinishedCell";
    self.headerIdentifier = @"FinishedHeader";
    
    [self layoutUI];
    [self layoutConstraints];
    [self refreshDataSource];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark =====================================================  user interface layout
-(void)layoutUI{
    self.headerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 60.f);
    [self.headerView addSubview:self.labelTitle];
    self.tableView.tableHeaderView = self.headerView;
    [self.tableView registerClass:[FinishedCell class] forCellReuseIdentifier:self.cellIdentifier];
    [self.tableView registerClass:[FinishedHeader class] forHeaderFooterViewReuseIdentifier:self.headerIdentifier];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.emptyDataSetSource = self;
    self.tableView.emptyDataSetDelegate = self;
}

-(void)layoutConstraints{
    self.labelTitle.translatesAutoresizingMaskIntoConstraints = NO;
    
    [self.headerView addConstraint:[NSLayoutConstraint constraintWithItem:self.labelTitle attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.headerView attribute:NSLayoutAttributeTop multiplier:1.0 constant:0.f]];
    [self.headerView addConstraint:[NSLayoutConstraint constraintWithItem:self.labelTitle attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.headerView attribute:NSLayoutAttributeLeft multiplier:1.0 constant:0.f]];
    [self.headerView addConstraint:[NSLayoutConstraint constraintWithItem:self.labelTitle attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.headerView attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0.f]];
    [self.headerView addConstraint:[NSLayoutConstraint constraintWithItem:self.labelTitle attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self.headerView attribute:NSLayoutAttributeRight multiplier:1.0 constant:0.f]];
    
}

#pragma mark =====================================================  DataSource
-(void)queryData{
    AFHTTPRequestOperationManager* mgr = [AFHTTPRequestOperationManager manager];
    NSDictionary* arg = @{@"ince":@"get_overorder_list",@"emp_id":self.Identity.userInfo.userID,@"page":[WMHelper integerConvertToString:self.page.pageIndex]};
    [mgr POST:kHost parameters:arg success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        [WMHelper outPutJsonString:responseObject];
        NSInteger flag = [[responseObject objectForKey:@"status"]integerValue];
        NSInteger totalCount = 0;
       __block NSInteger currentSections = 0;
        if(flag == 1){
            [self.arrayData removeAllObjects];
            totalCount = [[responseObject objectForKey: @"total"] integerValue];
            NSArray* array = [responseObject objectForKey:@"list"];
            if(![WMHelper isNULLOrnil:array]){
                [array enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    MFinishedTask* item = [[MFinishedTask alloc]initWithItem:obj];
                    self.page.recordCount+= [item.count integerValue];
                    currentSections ++;
                    [self.arrayData addObject:item];
                }];
            }
            [self loadData:[responseObject objectForKey:@"total"]];
        }else{
            [self alertHUD:[responseObject objectForKey:@"fail"]];
        }
        [self.tableView reloadData];
        if(self.page.pageIndex == 1 ){
        [self.tableView.mj_header endRefreshing];
        }else if (self.page.recordCount < totalCount){
            [self.tableView.mj_footer endRefreshing];
        }
        if(self.page.recordCount == totalCount){
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }
        self.page.groupSection += currentSections;
    } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
        [self alertHUD:@"网络异常"];
        [self.tableView.mj_header endRefreshing];
    }];
}

-(void)refreshDataSource{
    __weak typeof(self) weakSelf = self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.page.pageIndex = 1;
        weakSelf.page.recordCount = 0;
        weakSelf.page.groupSection = 0;
        [weakSelf queryData];
    }];
    self.tableView.mj_footer = [MJRefreshAutoStateFooter footerWithRefreshingBlock:^{
        weakSelf.page.pageIndex ++;
        [weakSelf queryData];
    }];
    
    [self.tableView.mj_header beginRefreshing];
}

#pragma mark =====================================================  <UITableVeiwDataSource>

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return  self.arrayData.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    MFinishedTask* empty = self.arrayData[section];
    return empty.arrayOrder.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    FinishedCell *cell = [tableView dequeueReusableCellWithIdentifier:self.cellIdentifier forIndexPath:indexPath];
     MFinishedTask* empty = self.arrayData[indexPath.section];
    cell.entity = empty.arrayOrder[indexPath.row];
    cell.arrayOrder = empty.arrayOrder;
    cell.tag = indexPath.row;
    UITapGestureRecognizer *tapgr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(gestureTouch:)];
    [cell addGestureRecognizer:tapgr];
    return cell;
}

#pragma mark =====================================================  <UITableViewDelegate>

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    MFinishedTask* empty = self.arrayData[indexPath.section];
    CGFloat height = 0.f;
    height+=100.f;
       MOrder* item = empty.arrayOrder[indexPath.row];
  
        for (NSString* str in item.arrayStore) {
            height+=35.f;
        }
    return height;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 45.f;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    FinishedHeader* header =  (FinishedHeader*)[tableView dequeueReusableHeaderFooterViewWithIdentifier:self.headerIdentifier];
    header.entity = self.arrayData[section];
    return header;
}

#pragma mark =====================================================  DZEmptyData 协议实现
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
{
    return [[NSAttributedString alloc] initWithString:@"没有已完成的任务!" attributes:@{NSFontAttributeName :[UIFont boldSystemFontOfSize:17.0],NSForegroundColorAttributeName:[UIColor grayColor]}];
}

- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView
{
    return roundf(self.tableView.frame.size.height/10.0);
}
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView
{
    return YES;
}

#pragma mark =====================================================  SEL
-(IBAction)gestureTouch:(UIGestureRecognizer*)sender{
    FinishedCell* cell = (FinishedCell*)sender.view;     
    FinishedTaskDetail* controller = [[FinishedTaskDetail alloc]init];
    controller.entity = cell.entity;
    [self.navigationController pushViewController:controller animated:YES];
}

#pragma mark =====================================================  private method
-(void)loadData:(NSString*)count{
    if(count){
        count = [NSString stringWithFormat:@"%@单",count];
        NSString* str = [NSString stringWithFormat:@"累计单量 : %@",count];
        NSMutableAttributedString* attributeStr = [[NSMutableAttributedString alloc]initWithString:str];
        [attributeStr addAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:24.f],NSForegroundColorAttributeName:[UIColor colorWithRed:248/255.f green:159/255.f blue:39/255.f alpha:1.0]} range:[str rangeOfString:count]];
        self.labelTitle.attributedText = attributeStr;
    }else{
        
    }
}

#pragma mark =====================================================  property package
-(UIView *)headerView{
    if(!_headerView){
        _headerView = [[UIView alloc]init];
        _headerView.backgroundColor = [UIColor whiteColor];
    }
    return _headerView;
}

-(UILabel *)labelTitle{
    if(!_labelTitle){
        _labelTitle = [[UILabel alloc]init];
        _labelTitle.textAlignment = NSTextAlignmentCenter;
    }
    return _labelTitle;
}

-(Pager *)page{
    if(!_page){
        _page = [[Pager alloc]init];
        _page.pageIndex = 1;
    }
    return _page;
}

-(NSMutableArray *)arrayData{
    if(!_arrayData){
        _arrayData = [[NSMutableArray alloc]init];
    }
    return _arrayData;
}

@end
